package org.antrain.pwd.controller;

import java.util.Map;
import javax.annotation.Resource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.antrain.pwd.pojo.Cipher;
import org.antrain.pwd.service.ICipherService;
import org.antrain.pwd.utils.InitUtil;
import org.antrain.pwd.utils.Result;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 密码表 前端控制器
 * </p>
 *
 * @author antrain
 * @since 2021-03-17
 */
@RestController
@RequestMapping("/ciphers")
@Slf4j
public class CipherController {
  @Resource
  private ICipherService cipherService;

  /**
   * 进行分页查询
   */
  @GetMapping
  public Result getList(@RequestParam Map<String, Object> param) {
    InitUtil.initPage(param);
    int num = Integer.parseInt(param.get("page").toString());
    int limit = Integer.parseInt(param.get("limit").toString());
    QueryWrapper<Cipher> wrapper = new QueryWrapper<>();
    String name = param.get("name").toString();
    if (!StrUtil.isBlank(name)) {
      wrapper.like("name", name).or().like("descr", name);
    }
    IPage<Cipher> page = new Page<>(num, limit);
    return Result.success(cipherService.page(page, wrapper));
  }

  /**
   * 通过主键id在表中查找信息
   */
  @GetMapping("/{id}")
  public Result getById(@PathVariable int id) {
    Cipher Cipher = cipherService.getById(id);
    if (Cipher == null) {
      return Result.failed("", "不存在");
    }
    return Result.success(Cipher);
  }

  /**
   * 向表中添加一条记录
   */
  @PostMapping()
  public Result save(@RequestBody Cipher cipher) {
    SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, preDeal(cipher.getSecretKey()).getBytes());
    cipher.setPassword(aes.encryptHex(cipher.getPassword()));
    if (cipherService.save(cipher)) {
      return Result.success("", "添加成功");
    }
    return Result.failed("", "添加失败");
  }

  @PostMapping("/decrypt")
  public Result decrypt(@RequestBody Cipher cipher){
    log.debug("cipher: {}",cipher);
    SymmetricCrypto aes =  new SymmetricCrypto(SymmetricAlgorithm.AES, preDeal(cipher.getSecretKey()).getBytes());
    String decryptStr = aes.decryptStr(cipher.getPassword(), CharsetUtil.CHARSET_UTF_8);
    return Result.success(decryptStr);
  }

  /**
   * 根据表中的主键修改 根据表中字段相应的修改，如果存在则修改
   */
  @PutMapping("/{id}")
  public Result update(@RequestBody Cipher cipher, @PathVariable int id) {
    cipher.setId(id);
    if (cipherService.updateById(cipher)) {
      return Result.success("", "修改成功");
    }
    return Result.failed("", "修改失败");
  }

  /**
   * 在数据表中真正的删除一条记录
   */
  @DeleteMapping("/{id}")
  public Result delById(@PathVariable int id) {
    if (cipherService.removeById(id)) {
      return Result.success("", "删除成功");
    }
    return Result.failed("", "删除失败");
  }

  /**
   * 将密钥变成16位
   * @param key
   * @return
   */
  private String preDeal(String key) {
    if (key.length()>16) return key.substring(0, 16);
    return StrUtil.fill(key, 'a', 16, false);
  }

}
